package com.heba.helper;

import android.content.Context;

import com.heba.Cfg;
import com.heba.Debug;
import com.heba.bean.diary.ItemImageTagObject;
import com.heba.bean.diary.ItemTagInfoObject;
import com.heba.bean.diary.ItemUploadPhotoObject;
import com.heba.bean.search.AccountSearchObject;
import com.heba.bean.search.HashTagSearchObject;
import com.heba.helper.callback.FileUploadListener;
import com.heba.helper.callback.PhotoCompressListener;
import com.heba.helper.callback.VideoUploadListener;
import com.heba.utils.FileSizeUtils;
import com.heba.utils.ImageTools;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.util.List;

import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * 圖片上壓縮和上傳處理
 * <p>
 * Created by jason on 2020/2/20.
 */
public class UploadPhotoHelper {

    private Context context;

    private FileUploadHelper fileUploadHelper;

    private int compressCount;

    private int uploadImageSize;  //需要壓縮的圖片數量

    private int uploadCount;   //上傳成功的次數

    public UploadPhotoHelper(Context context) {
        this.context = context;
        fileUploadHelper = new FileUploadHelper(context);
    }

    /**
     * 壓縮上傳的圖片
     */
    public void compressPhoto(List<ItemUploadPhotoObject> uploadPhotoObjects, PhotoCompressListener listener) {

        if (uploadPhotoObjects.isEmpty())
            return;

        compressCount = 0;

        uploadCount = 0;

        uploadImageSize = uploadPhotoObjects.size();

        for (ItemUploadPhotoObject object : uploadPhotoObjects) {

            if (object.getImageType() == ItemUploadPhotoObject.SHOW_IMAGE_ICON) {
                uploadImageSize = uploadPhotoObjects.size() - 1;
                continue;
            }

            Debug.Log("图片压缩前的大小---->",
                    FileSizeUtils.getFileOrFilesSize(object.getPhotoPath(), 2) + "KB");

            /**
             * 開始圖片壓縮
             */
            Luban.with(context)
                    .load(new File(object.getPhotoPath()))
                    .ignoreBy(100)
                    .setTargetDir(ImageTools.createFile(ImageTools.getUploadPathFolder(), "").getPath())
                    .setCompressListener(new OnCompressListener() {
                        @Override
                        public void onStart() {
                            // TODO 压缩开始前调用，可以在方法内启动 loading UI
                            Debug.Log("onStart", "開始圖片壓縮");
                            listener.onCompressStart();
                        }

                        @Override
                        public void onSuccess(File file) {
                            // TODO 压缩成功后调用，返回压缩后的图片文件
                            Debug.Log("onSuccess", "壓縮成功");
                            compressCount++;
                            object.setUploadPath(file.getPath());

                            Debug.Log("图片压缩后的大小 --->",
                                    FileSizeUtils.getFileOrFilesSize(file.getPath(), 2) + "KB");

                            Debug.Log("onSuccess",
                                    "compressCount is " + compressCount + ", uploadImageSize is " + uploadImageSize);

                            if (compressCount == uploadImageSize) {

                                Debug.Log("圖片全部壓縮成功", "開始進行圖片上傳");
                                listener.onCompressSuccess();

                                /**
                                 * 全部图片压缩成功,開始上傳圖片到騰訊雲
                                 */
                                for (ItemUploadPhotoObject photoObject : uploadPhotoObjects) {

                                    if (photoObject.getImageType() == ItemUploadPhotoObject.SHOW_IMAGE_ICON)
                                        continue;

                                    //图片上传本地服务器
                                    new MemberShipHelper(new MemberShipHelper.MembershipListener() {
                                        @Override
                                        public void Success() {
                                            uploadCount++;
                                            Debug.Log("upload onSuccess", "uploadCount = " + uploadCount);
                                            photoObject.setPhotoUrl(Cfg.uploadImageUrl);
                                            if (uploadCount == uploadImageSize) {
                                                listener.onUploadSuccess(uploadPhotoObjects);
                                            }
                                        }



                                        @Override
                                        public void Fail(String error) {
                                            listener.onUploadFailure();
                                        }
                                    }).uploadImage(context, photoObject.getUploadPath());

                                    //图片上传腾讯云
//                                    String cosPath = "greenmulu/image/transfer_" + ImageTools.getFileName();
//                                    fileUploadHelper.upload(photoObject.getUploadPath(), cosPath, new FileUploadListener() {
//                                        @Override
//                                        public void onSuccess(String imgUrl) {
//                                            /**
//                                             * 該方法在子線程執行
//                                             */
//                                            uploadCount++;
//                                            Debug.Log("upload onSuccess", "uploadCount = " + uploadCount);
//
//                                            photoObject.setPhotoUrl(imgUrl);
//
//                                            if (uploadCount == uploadImageSize) {
//                                                /**
//                                                 * 全部圖片上傳騰訊雲成功
//                                                 */
//                                                listener.onUploadSuccess(uploadPhotoObjects);
//                                            }
//                                        }
//
//                                        @Override
//                                        public void onFail() {
//                                            /**
//                                             * 該方法在子線程執行
//                                             */
//                                            listener.onUploadFailure();
//                                        }
//                                    });
                                }
                            }
                        }

                        @Override
                        public void onError(Throwable e) {
                            // TODO 当压缩过程出现问题时调用
                            Debug.Log("onError", "壓縮出錯");
                            listener.onCompressError();
                        }
                    }).launch();

        }

    }
    /**
     * 壓縮上傳的圖片
     */
    public void compressSamPhoto(File imageFile, FileUploadListener listener) {

        if (imageFile == null)
            return;



            /**
             * 開始圖片壓縮
             */
            Luban.with(context)
                    .load(imageFile)
                    .ignoreBy(100)
                    .setTargetDir(ImageTools.createFile(ImageTools.getUploadPathFolder(), "").getPath())
                    .setCompressListener(new OnCompressListener() {
                        @Override
                        public void onStart() {
                            // TODO 压缩开始前调用，可以在方法内启动 loading UI
                            Debug.Log("onStart", "開始圖片壓縮");

                        }

                        @Override
                        public void onSuccess(File file) {
                            // TODO 压缩成功后调用，返回压缩后的图片文件


                            Debug.Log("图片压缩后的大小 --->",
                                    FileSizeUtils.getFileOrFilesSize(file.getPath(), 2) + "KB");

                            Debug.Log("onSuccess",
                                    "compressCount is " + compressCount + ", uploadImageSize is " + uploadImageSize);
                            //图片上传本地服务器
                            new MemberShipHelper(new MemberShipHelper.MembershipListener() {

                                @Override
                                public void Success() {
                                }

                                @Override
                                public void SamSuccess(String imageUrl) {
                                    listener.onSuccess(imageUrl);
                                }

                                @Override
                                public void Fail(String error) {
                                    listener.onFail();
                                }
                            }).uploadSamImage(context, file.getPath());
                        }

                        @Override
                        public void onError(Throwable e) {
                            // TODO 当压缩过程出现问题时调用
                            Debug.Log("onError", "壓縮出錯");
                            listener.onFail();
                        }
                    }).launch();



    }
    /**
     * 上传视频缩略图和视频
     *
     * @param uploadPhotoObjects
     * @param listener
     */
    public void uploadVideo(List<ItemUploadPhotoObject> uploadPhotoObjects, VideoUploadListener listener) {
        if (uploadPhotoObjects.isEmpty())
            return;
        ItemUploadPhotoObject object = uploadPhotoObjects.get(0);

        /**
         * 上传视频缩略图
         */
        String cosPath = "greenmulu/image/transfer_" + ImageTools.getFileName();
        fileUploadHelper.upload(object.getPhotoPath(), cosPath, new FileUploadListener() {
            @Override
            public void onSuccess(String imgUrl) {
                //上传图片成功
                object.setPhotoUrl(imgUrl);

                /**
                 * todo 压缩视频操作
                 */


                /**
                 * 执行上传操作
                 */
                Debug.Log("执行视频上传操作 ", "");
                String cosVideoPath = "greenmulu/video/transfer_" + ImageTools.getVideoName();
                fileUploadHelper.upload(object.getVideoPath(), cosVideoPath, new FileUploadListener() {
                    @Override
                    public void onSuccess(String videoUrl) {
                        //上传视频成功
                        Debug.Log("视频上传成功 ", "");
                        object.setVideoUrl(videoUrl);
                        listener.onUploadSuccess(uploadPhotoObjects);
                    }

                    @Override
                    public void onFail() {
                        Debug.Log("视频上传失败 ", "");
                        listener.onUploadFailure();
                    }
                });

            }

            @Override
            public void onFail() {

            }
        });
    }

    /**
     * 生成上傳圖片的json字符串
     *
     * @param list 图片url集合
     * @return json
     */
    public String generatePhotoPathJson(List<ItemUploadPhotoObject> list) {
        if (null == list)
            return "";

        try {
            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < list.size(); i++) {
                ItemUploadPhotoObject uploadPhotoObject = list.get(i);
                if (uploadPhotoObject.getImageType() == ItemUploadPhotoObject.SHOW_IMAGE_ICON)
                    continue;

                JSONObject d = new JSONObject();

                /**
                 * 添加图片json
                 */
                d.put("ImageUrl", uploadPhotoObject.getPhotoUrl());
                d.put("ImageWidth", uploadPhotoObject.getImageWidth());
                d.put("ImageHeight", uploadPhotoObject.getImageHeight());
                d.put("VideoUrl", uploadPhotoObject.getVideoUrl());
                d.put("Type", uploadPhotoObject.getType().equals(ItemUploadPhotoObject.TYPE_PICTURE) ? "0" : "1");

                /**
                 * 添加paste 图片标记用户数组
                 */
                List<ItemImageTagObject> tagObjects = uploadPhotoObject.getImageTagObjectList();
                if (tagObjects == null || tagObjects.isEmpty()) {
                    d.put("Paste", "");
                } else {
                    JSONArray paste = new JSONArray();
                    for (int j = 0; j < tagObjects.size(); j++) {
                        ItemImageTagObject tagObject = tagObjects.get(j);
                        JSONObject object = new JSONObject();
                        object.put("UserID", tagObject.getUserID());
                        object.put("Pos_x", String.format("%.2f", tagObject.getScaleX()));
                        object.put("Pos_y", String.format("%.2f", tagObject.getScaleY()));
                        paste.put(paste.length(), object);
                    }
                    d.put("Paste", paste.toString());
                }

                jsonArray.put(jsonArray.length(), d);
            }
            Debug.Log("圖片上傳 PathJson ", jsonArray.toString());
            return jsonArray.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 生成話題標籤json字符串
     *
     * @param list
     * @return
     */
    public String generateTagJson(List<ItemTagInfoObject> list) {
        if (list == null || list.isEmpty())
            return "";
        try {
            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < list.size(); i++) {
                JSONObject d = new JSONObject();
                d.put("Content", list.get(i).getHotTalk());
                jsonArray.put(jsonArray.length(), d);
            }
            Debug.Log("話題標籤 TalkJson ", jsonArray.toString());
            return jsonArray.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
    /**
     * 生成話題標籤json字符串
     *
     * @param list
     * @return
     */
    public String generateTagInfoJson(List<HashTagSearchObject> list) {
        if (list == null || list.isEmpty())
            return "";
        try {
            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < list.size(); i++) {
                JSONObject d = new JSONObject();
                d.put("Content", list.get(i).getContent());
                jsonArray.put(jsonArray.length(), d);
            }
            Debug.Log("話題標籤 TalkJson ", jsonArray.toString());
            return jsonArray.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 生成話題標籤json字符串
     *
     * @param list
     * @return
     */
    public String generateUserInfoJson(List<AccountSearchObject> list) {
        if (list == null || list.isEmpty())
            return "";
        try {
            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < list.size(); i++) {
                JSONObject d = new JSONObject();
                d.put("UserID", list.get(i).getUserID());
                jsonArray.put(jsonArray.length(), d);
            }
            Debug.Log("用戶數組 JSON ", jsonArray.toString());
            return jsonArray.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 生成數組json字符串
     *
     * @param list
     * @return
     */
    public String generateImageListJson(List<String> list) {
        if (list == null || list.isEmpty())
            return "";
        try {
            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < list.size(); i++) {
                jsonArray.put(jsonArray.length(),list.get(i));
            }
            Debug.Log("用戶數組 JSON ", jsonArray.toString());
            return jsonArray.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


}
